<template>
  <div class="app-container">

    
     <query-panel @query = 'handleFilter' @reset="handleReset" 
          :showOpen="false" labelWidth="100px">
         

          <el-form-item label="工号">
            <el-input v-model="listQuery.id" class="filter-item" placeholder="请输入工号" maxlength="10"   clearable=""/>      
          </el-form-item>

          <el-form-item label="姓名">
            <el-input v-model="listQuery.name" class="filter-item" placeholder="请输入姓名" maxlength="10"   clearable=""/>      
          </el-form-item>
            
        </query-panel>


    <!-- 收费区间 -->
    <div class="filter-container" style="clear: both;">
      <el-button
        class="filter-item"
        type="primary"
        :icon="Refresh"
        @click="handleFilter"
        >刷新</el-button
      >
      <el-button class="filter-item" type="primary" @click="handleAdd">新增用户</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      :height="tableHeight() + 4"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        align="center"
        min-width="250"
        label="用户工号"
        prop="id"
      />
      <el-table-column
        align="center"
        min-width="250"
        label="姓名"
        prop="name"
      >
       
      </el-table-column>

       <el-table-column
        align="center"
        label="角色"
        min-width="250"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template #default="scope">          
          <el-tag style="margin-left: 10px;" v-for="r in scope.row.userRoles">{{ r.name }}</el-tag>
        </template>
      </el-table-column>
 

      <el-table-column
        align="center"
        label="操作"
        min-width="250"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template #default="scope">          
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pageHolder">
      <el-pagination
        background
        v-model:page-size="listQuery.limit"
        layout="total,sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="pageChange"
        @size-change="handleSizeChange"
      />
    </div>

    

     <!-- 新增/编辑角色对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="80%"
    >
      <el-form :model="userForm" label-width="100px">
         <el-form-item label="人员信息" prop="staffId">
          <el-input
            :value="userIdAndName"
            maxlength="10"
            style="width: 250px"
            clearable=""
            required
            readonly            
            placeholder="请选择"
            @click="handleAddUser"
          >            
          </el-input>                    
          <el-button  type="primary" @click="handleAddUser">
                选择人员</el-button>
        </el-form-item>

         

        
        <el-form-item label="授权角色">
          <el-transfer
            v-model="userForm.userRoles"
            :data="roleOptions"
            :titles="['可选角色', '已选角色']"
            :props="{ key: 'id', label: 'name' }"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
 <el-dialog
      title="选择人员"
      v-model="showSelectUser"      
      :close-on-click-modal="false"
      width="60%"
      :close-on-press-escape="false"
    >
      <user-select ref="userSelect" @select="handleSelectUser" />

      <template #footer>
        <el-button @click="showSelectUser = false">取 消</el-button>
      </template>
    </el-dialog>
   
  </div>
</template>

 
<script setup lang="ts">
import { tableHeight } from "@/util/index.ts";
import configs from "@/util/config.ts";
import http from "@/api/js/http";

import { ref, reactive, onMounted ,computed} from "vue";
import msg from "@/util/Message.ts";
import { Refresh } from "@element-plus/icons-vue";
import { ElMessage,  } from 'element-plus'
import  {ISysRole} from '@/types/index.ts'
import UserSelect from "@/components/select/UserSelect.vue";

const showSelectUser = ref(false);
const dialogVisible = ref(false)
const dialogTitle = ref('新增角色')


const userForm = reactive({
  id: null,
  name: '',
  userRoles: []
})




const list = ref<any>([]);
const isEdit = ref(false)
const isAdd = ref(false)

const total = ref<number>(0);
const listLoading = ref(true);
const listQuery = reactive({
  page: 1,
  id: null,
  name:null,
  limit: configs.limit,
});

function handleAddUser() {
  showSelectUser.value = true;
}

const userIdAndName = computed(()=>{
  if(!userForm.id) return ''
  return userForm.id + "("+userForm.name+")";
})
 

const roleOptions = ref<ISysRole[]>([])


 

onMounted(() => {
  getAllMenuList();
  getList();
});


function pageChange(page: number) {
  listQuery.page = page;
  getList();
}
 

// 打开编辑对话框
//@ts-ignore
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户授权'
  //currentRoleId.value = row.id
  userForm.id = row.id
  userForm.name = row.name
  dialogVisible.value = true

  const roles:string[] = [];
  row.userRoles.forEach((ele:ISysRole)=>{
    if(ele.id)roles.push(ele.id);
  })

  //@ts-ignore
  userForm.userRoles = roles;
}
 

 

function handleSelectUser(obj: any) {
  userForm.id = obj.staffId;
  userForm.name = obj.staffName;
  showSelectUser.value = false;
}

// 打开新增对话框
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  userForm.id = null
  userForm.name = ''
  userForm.userRoles = []
  dialogVisible.value = true
  isAdd.value= true;
  isEdit.value=false;
  
}

function handleReset(){
  resetQuery();
  handleFilter();
}
 
 
function handleSizeChange() {
  getList();
}

 
function getAllMenuList() {
  listLoading.value = true;

  http
    .get<ISysRole[]>("/admin/permission/roleList")
    .then((resp) => {
      var respList = resp?.data;
      if(respList)roleOptions.value = respList;
    });
      
}

function getList() {
  listLoading.value = true;

  http
    .get("/admin/permission/userList",listQuery)
    .then((resp) => {
      //@ts-ignore
      var respList = resp?.data.list;
      list.value = respList;
      listLoading.value = false;
      //@ts-ignore
      total.value = resp.data.total;
    })
    .catch(() => {
      list.value = [];
      total.value = 0;
      listLoading.value = false;
    });
}

function resetQuery(){
  listQuery.page = 1;
  listQuery.limit = configs.limit;
  listQuery.name = null;
  listQuery.id = null;
  
}

function handleFilter() {
  listQuery.page = 1;
  getList();
}

function handleDelete(row: any) {
  msg.delConfirm().then(() => {
    doDelete(row);
  });
}

function doDelete(row: any) {
  var data = "userId=" + row.id;

  http
    .post("/admin/permission/deleteUser", data)
    .then(() => {
      msg.success("删除成功");
      getList();
    })
    .catch(() => {
      msg.error("删除失败");
    });
}

 

// 提交表单
const submitForm = () => {
  if (!userForm.id) {
    ElMessage.warning('请选择人员')
    return
  }
  
   const userRoles:ISysRole[] = [];
   userForm.userRoles.forEach((ele)=>{
    userRoles.push({
      id:ele
    })
   })

 
  http.post('/admin/permission/saveUserRole',{
    id:userForm.id,
    userRoles
  })
  .then((resp)=>{
    if(resp.code == 0){
      ElMessage.success('新增成功')
      dialogVisible.value = false
      getList();
    }else{
      msg.error(resp.msg);
    }
    
  });

 
  
}
</script>
